package com.zju.cst.classification.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

public class Similarity {

	public static BigDecimal calculate(Map<String, Integer> trainedData, Map<String, Integer> targetData){
		BigDecimal result = new BigDecimal(0.0d);
		//计算分子，向量积
		for(String key : trainedData.keySet()){
			if(targetData.containsKey(key)) result = result.add(new BigDecimal(trainedData.get(key) * targetData.get(key)));
		}
		//计算分母
		BigDecimal fenmu = getMod(targetData).multiply(getMod(trainedData));
		result = result.divide(fenmu, 10, RoundingMode.HALF_UP);
		return result;
	}
	
	public static BigDecimal getMod(Map<String, Integer> map){
		BigDecimal result = new BigDecimal(0.0d);
		for(String key : map.keySet()){
			result = result.add(new BigDecimal(Math.pow(map.get(key),2)));
		}
		result = new BigDecimal(Math.sqrt(result.doubleValue()));
		return result;
	}
	
}
